import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { UserModule } from './modules/user/user.module';
import { ArticleModule } from './modules/article/article.module';
import { CommentModule } from './modules/comment/comment.module';
import { UploadModule } from './modules/upload/upload.module';
import { LoginModule } from './modules/login/login.module';
import { CategoryModule } from './modules/category/category.module';
import { TagModule } from './modules/tag/tag.module';
import { ConfigModule as AppConfigModule } from './modules/config/config.module';
import { LikeModule } from './modules/like/like.module';
import { CommonModule } from './modules/common/common.module';
import { LogModule } from './modules/log/log.module';
import { User } from './entities/user.entity';
import { Article } from './entities/article.entity';
import { Comment } from './entities/comment.entity';
import { Category } from './entities/category.entity';
import { Like } from './entities/like.entity';
import { Tag } from './entities/tag.entity';
import { Config } from './entities/config.entity';
import { JwtAuthGuard } from './middlewares/auth/jwt-auth.guard';
import { JwtStrategy } from './middlewares/auth/jwt.strategy';
import { RoleGuard } from './middlewares/auth/role.guard';
import { LoggerMiddleware } from './middlewares/logger.middleware';
import { Log } from './entities/log.entity';

@Module({
  imports: [
    ConfigModule.forRoot({ //next 配置模块，集成了 dotenv 功能。
      isGlobal: true,
    }),
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: process.env.DB_HOST,
      port: parseInt(process.env.DB_PORT || '3306'),
      username: process.env.DB_USERNAME,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_DATABASE,
      entities: [User, Article, Comment, Category, Like, Tag, Config, Log],
      synchronize: true, // 开发环境下使用，生产环境下建议关闭
      autoLoadEntities: true,
      // 添加连接池配置
      extra: {
        connectionLimit: 10, // 连接池最大连接数
        acquireTimeout: 60000, // 获取连接超时时间（毫秒）
        timeout: 60000, // 连接超时时间（毫秒）
        reconnect: true, // 启用自动重连
      },
      // 添加连接超时和重试配置
      connectTimeout: 20000, // 初始连接超时时间（毫秒）
      retryAttempts: 3, // 重试次数
      retryDelay: 3000, // 重试延迟（毫秒）
    }),
    UserModule,
    ArticleModule,
    CommentModule,
    UploadModule,
    LoginModule,
    CategoryModule,
    TagModule,
    AppConfigModule,
    LikeModule,
    CommonModule,
    LogModule,
  ],
  controllers: [AppController],
  providers: [
    JwtStrategy,
    {
      provide: APP_GUARD, //全局授权守卫  ， 除了@public 装饰器
      useClass: JwtAuthGuard,
    },
    {
      provide: APP_GUARD, //全局角色守卫  ，如果没有设置需要的角色(@Admin)，则默认允许访问
      useClass: RoleGuard,
    },
  ],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}